require "vector"
require "std"

function d4()
  local object={}

  -- every object needs a mass, angular mass, position, angular velocity, etc, etc.
  object.position=Vector{0,0,0}
  object.mass=1
  object.velocity=Vector{0,0,0}
  object.angularMass=1
  object.angularVelocity=Vector{0,0,0}
  object.color=0xFFFF00
  object.radius=0.7
  
  -- every object has a list of vertices that take part in the physics simulation.
  object.vertices={
    {1,-1,-1},{-1,1,-1}, {1,1,1},{-1,-1,1}
  }
  table.transform(object.vertices, Vector)

  table.transform(object.vertices, func.pbind(__mul,0.5))  

  
  
  -- every object has a set of surfaces that hold the polygons and the textures
  local polygons=verticesToPolygons(object.vertices)
  object.surfaces=table.transform(polygons,polygonToSurface)
  
  --a d4 has three textures per face, one for each corner
  for i,surface in ipairs(object.surfaces) do
    for i=1,3 do 
      local texture={
        image=table.index(object.vertices, surface.polygon[i])..".png",
        o=math.avg(surface.center, surface.polygon[i]),
        y=math.avg(surface.polygon[i],surface.polygon[i], surface.polygon[i], surface.center),
        next=surface.texture
      }
      texture.y=2*texture.o-texture.y
      texture.x=vector.cross(surface.normal,(texture.y-texture.o))+texture.o
      surface.texture=texture
    end
  end
  
  -- every object also has a set of vectors that need to be updated with rotation.
  object.allVertices=extractAllVertices(object)

  -- also surfaces refer back to their parent object
  for i,surface in ipairs(object.surfaces) do 
    surface.object=object
  end
  
return object end
